<?php

namespace App\Admin\Forms;

use Dcat\Admin\Widgets\Form;

class emailForm extends Form
{
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        foreach ($input as $key => $value) {
            admin_setting([$key => $value]);
        }

        return $this
                ->response()
                ->success('保存成功')
                ->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->hidden('_token')->value(csrf_token()); // 添加 CSRF 令牌
        $this->text('smtp_host')->default(admin_setting('smtp_host', 'smtp.example.com'))->required()->label('SMTP服务器');
        $this->text('smtp_username')->default(admin_setting('smtp_username', 'user@example.com'))->required()->label('SMTP帐户');
        $this->text('smtp_password')->default(admin_setting('smtp_password', 'password'))->required()->label('SMTP密码');
        $this->number('smtp_port')->default(admin_setting('smtp_port', 587))->required()->label('SMTP端口');
        $this->select('smtp_encryption')->options([
            '' => '关闭',
            'ssl' => 'SSL',
            'tls' => 'TLS',
        ])->default(admin_setting('smtp_encryption', 'tls'))->label('SMTP安全');
        $this->email('from_address')->default(admin_setting('from_address', 'user@example.com'))->required()->label('发送邮箱');
        $this->text('from_name')->default(admin_setting('from_name', 'Example Name'))->required()->label('邮箱名称');
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return [
            'smtp_host'  => admin_setting('smtp_host', 'smtp.example.com'),
            'smtp_username' => admin_setting('smtp_username', 'user@example.com'),
            'smtp_password' => admin_setting('smtp_password', 'password'),
            'smtp_port' => admin_setting('smtp_port', 587),
            'smtp_encryption' => admin_setting('smtp_encryption', 'tls'),
            'from_address' => admin_setting('from_address', 'user@example.com'),
            'from_name' => admin_setting('from_name', 'Example Name'),
        ];
    }
}
